package com.chcit.mobile.mvp.inventory.fragment.move;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chcit.custom.view.loader.QuickLoader;
import com.google.android.material.tabs.TabLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.loader.LoadingDialog;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.mvp.common.adapter.PackageScanAdapter;
import com.chcit.mobile.mvp.entity.MovementPlanBean;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.chcit.mobile.mvp.inventory.di.component.DaggerMovementPlanScanPackageComponent;
import com.chcit.mobile.mvp.inventory.contract.MovementPlanScanPackageContract;
import com.chcit.mobile.mvp.inventory.presenter.MovementPlanScanPackagePresenter;

import com.chcit.mobile.R;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.toast.XToast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

public class MovementPlanScanPackageFragment extends ScanFragment<MovementPlanScanPackagePresenter> implements MovementPlanScanPackageContract.View {

    private MovementPlanBean movementPlanBean;
    private PackageBean packageBean;

    @BindView(R.id.tiet_movement_plan_scan_package_no)
    SuperInputEditText tietNo;
    @BindView(R.id.tv_movement_plan_scan_package_productName)
    TextView tvProductName;
    @BindView(R.id.tv_movement_plan_scan_package_productSpec)
    TextView tvProductSpec;
    @BindView(R.id.tv_movement_plan_scan_package_manufacturer)
    TextView tvManufacturer;
    @BindView(R.id.tv_movement_plan_scan_package_lot)
    TextView tvLot;
    @BindView(R.id.tv_movement_plan_scan_package_guaranteeDate)
    TextView tvGuaranteeDate;
    @BindView(R.id.tv_movement_plan_scan_package_qtyPlan)
    TextView tvQtyPlan;
    @BindView(R.id.tv_movement_plan_scan_package_qtyMoved)
    TextView tvQtyMoved;
    @BindView(R.id.tv_movement_plan_scan_package_qtyMoving)
    TextView tvQtyMoving;
    @BindView(R.id.tv_movement_plan_scan_package_qtyLeft)
    TextView tvQtyLeft;
    @BindView(R.id.tv_movement_plan_scan_package_locator)
    TextView tvLocator;
    @BindView(R.id.bt_movement_plan_scan_package_ok)
    Button btOk;
    @BindView(R.id.tl_tabs)
    TabLayout tlTabs;
    @BindView(R.id.rv_movement_list)
    RecyclerView mRecyclerView;
    private int position;

    private BigDecimal  qtyLeft, qtyMoving;

    private List<PackageBean> donePackageBeans = new ArrayList<>();
    private PackageScanAdapter doneScanAdapter;
    private List<PackageBean> unPackageBeans = new ArrayList<>();
    private PackageScanAdapter unScanAdapter;

    public static MovementPlanScanPackageFragment newInstance(MovementPlanBean movementPlanBean) {
        MovementPlanScanPackageFragment fragment = new MovementPlanScanPackageFragment();
        fragment.movementPlanBean = movementPlanBean;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerMovementPlanScanPackageComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_movement_plan_scan_package, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        showTaskInfo();
        getData();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        tietNo.setText(barcodeData);
        checkPackageNo(barcodeData);
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initEvent();
        initDoneScanRecyclerView();
    }

    //操作
    @SuppressLint("SetTextI18n")
    private void showTaskInfo() {
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l->{
            assert mPresenter != null;
            if(mPresenter.isError){
                setFragmentResult(RESULT_OK,new Bundle());
            }
            pop();
        });

        tvProductName.setText(movementPlanBean.getProductName());
        tvProductSpec.setText(movementPlanBean.getProductSpec());
        tvManufacturer.setText(movementPlanBean.getManufacturer());
        tvLot.setText(movementPlanBean.getLot());
        tvGuaranteeDate.setText(movementPlanBean.getGuaranteeDate());

        tvQtyPlan.setText((movementPlanBean.getQtyPlaned().intValue()  + movementPlanBean.getUomName()));
        tvQtyMoved.setText((movementPlanBean.getQtyConfirmed().intValue() +  movementPlanBean.getUomName()));
        tvQtyMoving.setText("0" + movementPlanBean.getUomName());
        tvQtyLeft.setText((movementPlanBean.getQtyLeft().intValue()  + movementPlanBean.getUomName()));

        qtyLeft = movementPlanBean.getQtyLeft();
        qtyMoving = qtyLeft.subtract(qtyLeft);

        tvLocator.setText(movementPlanBean.getToLocatorValue());

        btOk.setEnabled(false);
    }

    /**
     *
     * @param packageNo
     */
    private void checkPackageNo(String packageNo) {
        if (tlTabs.getSelectedTabPosition() != 0) {
            Objects.requireNonNull(tlTabs.getTabAt(0)).select();
        }
        packageBean = new PackageBean(packageNo);
        int itemPosition = unPackageBeans.indexOf(packageBean);

        if (itemPosition >= 0) {
            if (qtyLeft.intValue() == 0) {
                String message = "<font color='#FF0000'><big>该任务要求的包装数量扫描完毕！</big></font><br/>(如需替换，请重新输入要替换的包装将该包装移除出已扫包装列表！)";
                new MaterialDialog.Builder(mContext)
                        .content(Html.fromHtml(message))
                        .title("提示")
                        .positiveText("确认")
                        .show();
                return;
            }

            packageBean = unPackageBeans.get(itemPosition);

            if (qtyLeft.subtract(packageBean.getUnitPackQty()).intValue() < 0) {
                String message = "<font color='#FF0000'><big>已超出该任务要求的包装数量！</big></font>";
                new MaterialDialog.Builder(mContext)
                        .content(Html.fromHtml(message))
                        .title("提示")
                        .positiveText("确认")
                        .show();
                return;
            }

            doneScanAdapter.addData(packageBean);
            unScanAdapter.remove(itemPosition);
            updateAddPackageInfo(packageBean);

            if(qtyLeft.intValue() == 0){
                String message = "<font color='#FF0000'>该任务要求的包装数量扫描完毕，是否确认移库？</font>";
                MaterialDialog materialDialog =  new MaterialDialog.Builder(mContext)
                        .title("确认移库")
                        .content(Html.fromHtml(message))
                        .positiveText("是")
                        .negativeText("否")
                        .onPositive((dialog, which) -> {
                            btOk.performClick();
                        })
                        .build();
                materialDialog.getActionButton(DialogAction.POSITIVE).setTextSize(18);
                materialDialog.getActionButton(DialogAction.NEGATIVE).setTextSize(18);
                materialDialog.show();
            }
        } else if ((itemPosition = donePackageBeans.indexOf(packageBean)) >= 0) {
            final int i = itemPosition;
            new MaterialDialog.Builder(mContext)
                    .content("该包装已扫过，是否删除改包装？")
                    .positiveText("否")
                    .negativeText("是")
                    .onNegative((dialog, which) -> {
                        packageBean = donePackageBeans.get(i);
                        unScanAdapter.addData(packageBean);
                        doneScanAdapter.remove(i);
                        updateSubstractPackageInfo(packageBean);
                    }).show();
        } else {
            DialogUtil.showErrorDialog(mContext, "该包装不是未扫包装");
        }
    }

    /**
     * 增加包装
     * @param packageBean 包装信息
     */
    @SuppressLint("SetTextI18n")
    private void updateAddPackageInfo(PackageBean packageBean) {
        qtyLeft = qtyLeft.subtract(packageBean.getUnitPackQty());
        qtyMoving = qtyMoving.add(packageBean.getUnitPackQty());

        tvQtyLeft.setText(qtyLeft.toString() + movementPlanBean.getUomName());
        tvQtyMoving.setText(qtyMoving.toString() + movementPlanBean.getUomName());

        btOk.setEnabled(true);
    }

    /**
     * 移除包装
     *
     * @param packageBean 包装信息
     */
    @SuppressLint("SetTextI18n")
    private void updateSubstractPackageInfo(PackageBean packageBean) {
        qtyLeft = qtyLeft.add(packageBean.getUnitPackQty());
        qtyMoving = qtyMoving.subtract(packageBean.getUnitPackQty());

        tvQtyLeft.setText(qtyLeft.toString() + movementPlanBean.getUomName());
        tvQtyMoving.setText(qtyMoving.toString() + movementPlanBean.getUomName());

        if (qtyLeft.intValue() > 0) {
            btOk.setEnabled(true);
        }
        else {
            btOk.setEnabled(false);
        }

    }

    private void initEvent() {
        tietNo.setOnKeyListener(new View.OnKeyListener() {
            private static final int LIMIT_TIME = 300;
            private long lastClickTime = 0;

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                long curTime = Calendar.getInstance().getTimeInMillis();
                if (curTime - lastClickTime > LIMIT_TIME) {
                    lastClickTime = curTime;
                    if (keyCode == KeyEvent.KEYCODE_ENTER && !tietNo.getText().toString().isEmpty()) {
                        onBarcodeEventSuccess(tietNo.getText().toString());
                        return true;
                    } else {
                        return false;
                    }
                }
                return false;

            }
        });
        tlTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        mRecyclerView.setAdapter(unScanAdapter);
                        break;
                    case 1:
                        mRecyclerView.setAdapter(doneScanAdapter);
                        break;
                }
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    private void initDoneScanRecyclerView() {
        doneScanAdapter = new PackageScanAdapter(donePackageBeans);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        doneScanAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            int itemClickPosition = -1;

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (itemClickPosition >= 0) {
                    doneScanAdapter.notifyItemChanged(itemClickPosition);
                    doneScanAdapter.setThisPosition(position);
                    itemClickPosition = position;
                    doneScanAdapter.notifyItemChanged(doneScanAdapter.getthisPosition());
                    // PackageBean packageBean= (PackageBean) adapter.getData().get(position);

                }
            }
        });
    }

    //获取待扫列表
    private void getData() {
        JSONObject data = new JSONObject();

        data.put("warehouseId", movementPlanBean.getWarehouseId());
        data.put("productId", movementPlanBean.getProductId());
        data.put("packageStatus", "S");
        data.put("lot", movementPlanBean.getLot());
        data.put("guaranteeDate", movementPlanBean.getGuaranteeDate());
        data.put("vendorId", "");
        data.put("locatorId", movementPlanBean.getLocatorId());

        assert mPresenter != null;
        mPresenter.getPakcageInfo(data, result -> {
            if(result.size()>0){
                if(result.get(0).getWarehouseId() != HttpClientHelper.getSelectWareHouse().getId()){
                    DialogUtil.showErrorDialog(mContext,"扫码失败，包装不在当前仓库:" +result.get(0).getPackageNo());
                    return;
                }

                unPackageBeans = result;
                initUnScanRecyclerView();
            }
        });
    }

    private void initUnScanRecyclerView() {
        unScanAdapter = new PackageScanAdapter(unPackageBeans);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //  mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));

        unScanAdapter.setOnItemClickListener((adapter, view, position) -> {
            unScanAdapter.notifyItemChanged(unScanAdapter.getthisPosition());
            unScanAdapter.setThisPosition(position);
            MovementPlanScanPackageFragment.this.position = position;
            PackageBean packageBean = (PackageBean) adapter.getData().get(position);
            tietNo.setText(packageBean.getPackageNo());
            unScanAdapter.notifyItemChanged(unScanAdapter.getthisPosition());
        });
        mRecyclerView.setAdapter(unScanAdapter);

    }

    //确认按钮按下事件
    @OnClick(R.id.bt_movement_plan_scan_package_ok)
    public void onViewClicked() {
        if (donePackageBeans.size() > 0) {
            confirm();
        } else {
            DialogUtil.showErrorDialog(mContext, "已扫包装不能为空");
        }
    }

    //移库确认
    private void confirm() {
        JSONObject data = new JSONObject();
        data.put("movementPlanId", movementPlanBean.getMovementPlanId());//
        data.put("movementPlanLineId", movementPlanBean.getMovementPlanLineId());

        JSONArray packageNos = new JSONArray();
        for (PackageBean p : donePackageBeans) {
            packageNos.add(p.getPackageNo());
        }

        data.put("packageNo", packageNos);

        mPresenter.movementPackageSubmit(data, () -> {
            showMessage("处理成功");
            setFragmentResult(RESULT_OK, new Bundle());
            pop();
        });
    }
}
